#!/usr/bin/python
# -*- coding: utf8 -*-
from commands import getoutput
import re

import xmpp
from plugin import Plugin

class PingModule(Plugin):
    infos = {'name': 'Ping',
            'author': 'magnetik',
            'version': '0.1',
            'website':'http://blog.magnetik.org',
            'handlers': ['ping'],
            'cmd': 'ping',
            }
    doc=_(u"Commande retourtant le ping d'un host ou d'une ip")
            
    def ping(self,conn,user,command,args,mess,lang):
        ip=args.split(' ',1)[0]
        test=re.search(r"(^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)|(^([a-zA-Z0-9]+)(\.[a-zA-Z]{1,4})+$)",ip)
        if test == None:
            conn.send(xmpp.protocol.Message(mess.getFrom(),_(u"Entrez une ip ou un domaine valide !"),"chat"))  
        else :
            com=u"ping -c 1 -q -w 2 " + ip
            #[0-9]{1,3}\.){3}[0-9]{1,3} < MATCH IP !
            #(\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3})
            temp=getoutput(com.encode('utf-8'))
            m=re.search(r"(.*)([0-9]*)(\.[0-9]*)/([0-9]*)(\.[0-9]*)/([0-9]*)(\.[0-9]*)/([0-9]*)(\.[0-9]*)(.*)",temp)
            if not m :
                conn.send(xmpp.protocol.Message(mess.getFrom(),_(u"Impossible de récuperer le ping de « %s »")%ip,"chat"))
            else :
                conn.send(xmpp.protocol.Message(mess.getFrom(),_(u"Ping de %(host)s : %(ping)s ms") % { 'host': ip, 'ping' : m.group(4)},"chat"))
